<template>
  <div>
    <div class="toolbar">
      <el-form :inline="true" :model="q" size="mini">
        <!-- <el-form-item label="代理ID">
          <el-input v-model="q.agency_name" placeholder="代理账号" prefix-icon="el-icon-edit"></el-input>
        </el-form-item> -->
        <el-form-item label="代理账号:">
          <!--<el-input v-model="q.id" placeholder="代理账号" prefix-icon="el-icon-edit"></el-input>-->

          <el-select v-model="q.id" clearable filterable placeholder="请输入">
            <el-option v-for="item of AgencyMainList" :key="item.id" :label="item.id+'>'+item.user_name+'>'+item.nickname"
                       :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联商户:">
          <el-select v-model="q.mch_id" clearable placeholder="请选择">
            <el-option label="所有" :value=null></el-option>
            <el-option v-for="(item,index) in MerchantsList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="安全码状态:">
          <el-select v-model="q.use_vcode" clearable placeholder="请选择">
            <el-option label="所有" :value=null></el-option>
            <el-option
              v-for="item in [{id:true,name:'开启'},{id:false,name:'关闭'}]"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="白名单状态:">
          <el-select v-model="q.use_white_ips" clearable placeholder="请选择">
            <el-option label="所有" :value=null></el-option>
            <el-option
              v-for="item in [{id:true,name:'已配置'},{id:false,name:'未配置'}]"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="可用状态:" >
          <el-select v-model="q.enable" clearable>
            <el-option label="所有" :value=null></el-option>
            <el-option value="true" label="可用"></el-option>
            <el-option value="false" label="禁用"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="工作状态:"  v-if="isSubagent">
          <el-select v-model="q.working" clearable placeholder="请选择">
            <el-option label="所有" :value=null></el-option>
            <el-option
              v-for="item in [{id:true,name:'工作中'},{id:false,name:'休息中'}]"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button type="danger" @click="reload">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row type="flex" class="row-bg btn-row" justify="end">
      <el-button size="mini" @click="add" v-if="!isSubagent" type="primary" icon="el-icon-plus">新增总代</el-button>
    </el-row>
    <el-table :data="listData.items" v-loading.body="listLoading" @sort-change="sortlist" size="mini" stripe border fit
              highlight-current-row>
      <el-table-column prop="id" label='代理ID' width="100"></el-table-column>

      <!-- <el-table-column prop="agency_type" label='代理类型' width="100" :formatter="typeFormartter"></el-table-column> -->
      <el-table-column prop="user_name" label='代理账号' width="140"></el-table-column>
      <el-table-column prop="nickname" label='代理昵称' v-if="isSubagent" width="140"></el-table-column>
      <el-table-column prop="avatar" label='头像' v-if="isSubagent" width="60">
        <template slot-scope="scope" v-if="isSubagent">
          <img :src="avatar+scope.row.avatar"   style=" width: 35px; height:35px ;border-radius: 50%; "/>
        </template>
      </el-table-column>
      <el-table-column prop="parent_name" v-if="isSubagent" label='所属总代' width="120">
        <template slot-scope="scope" v-if="scope.row.parent">{{scope.row.parent.user_name}}</template>
      </el-table-column>
      <el-table-column prop="mchs" label='关联商户' width="240" :formatter="typeFormartter"></el-table-column>
      <el-table-column prop="balance" label='余额' width="100"></el-table-column>
      <el-table-column prop="use_vcode" label='安全码状态' width="120" :formatter="typeFormartter"></el-table-column>
      <el-table-column prop="warning_amount" v-if="isSubagent" label='预警金额' width="100"></el-table-column>
      <el-table-column label='白名单状态' prop="white_ips"  width="120">
        <template slot-scope="scope">{{scope.row.white_ips?"已配置":"未配置"}}</template>
      </el-table-column>

      <el-table-column prop="enable" label='可用状态' width="100" :formatter="typeFormartter"></el-table-column>
      <!-- <el-table-column prop="min_amount" label='充值下限' width="120"></el-table-column>
      <el-table-column prop="max_amount" label='充值上限' width="120"></el-table-column> -->
      <el-table-column prop="working" v-if="isSubagent" label='工作状态' width="100" :formatter="typeFormartter"></el-table-column>

      <!--      <el-table-column prop="enable" label='代理状态' width="100" :formatter="typeFormartter"></el-table-column>-->
      <el-table-column prop="remark" label='备注' width="300"></el-table-column>
      <el-table-column prop="created_at" label='创建时间' sortable width="180"></el-table-column>
      <el-table-column prop="updated_at" label='更新时间' sortable width="180"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope" v-if="scope.row.agency_type == 2
">
          <div>
            <el-button type="success" size="mini" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button type="primary" size="mini" @click="update(scope.row)">编辑</el-button>
            <!--            <el-button :type="scope.row.enable ?'info':'danger'" size="mini" @click="enbleAgentMag(scope.row)">{{-->
            <!--              scope.row.enable?"禁用":"启用"}}-->
            <!--            </el-button>-->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="q.page_no" :page-sizes="$store.state.app.pageSizeArr"
                     :page-size="q.page_size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="listData.total">
      </el-pagination>
    </div>
    <save-update v-if="showUpdate" :showUpdate.sync="showUpdate" :id="show_id" :AgencyType="AgencyType"
                 :MerchantsList="MerchantsList"></save-update>
  </div>
</template>

<script>
  import saveUpdate from './saveUpdate'
  import {getAgencyList, deleteAgency, resetAgencyPassword, getMerchantsList, enbleAgentMag, openAgentMag} from '@/api'
  import {queryFilter} from '@/utils/patch'
  import {useVcode} from "../../utils/CommonJs";

  export default {
    components: {saveUpdate},
    computed:{
      // 是否是子代管理
      isSubagent(){
        return this.$route.name ==='Subagent'
      },
      agentString(){
        return this.isSubagent?'子代':'总代'
      }
    },
    data() {
      return {
        listData: {},
        q: {page_size: 30, page_no: 1},
        listLoading: false,
        showUpdate: false,
        settleCycle: this.$store.state.app.settleCycle,
        show_id: null,
        MerchantsList: [],
        AgencyMainList: [],
        AgencyType: this.$store.state.app.AgencyType,
        isEnable: false,
        btnType: 'warning',
        avatar: 'http://image.barchain.net/',
        resetPwdMeg: false
      }
    },
    activated() {
      this.getList()
    },
    created(){
      this.getMerchantsList()
      this.getAgencyList()
    },
    deactivated() {
      this.listLoading = false
    },
    methods: {
      add() {
        if (this.resetPwdMeg) {
          this.resetPwdMeg.close();
        }
        this.show_id = null
        this.showUpdate = true
      },
      resetPwd(row) {
        this.$confirm(`是否确认重置 ${row.user_name} 的密码？`, '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          useVcode(this,()=>{
            if (this.resetPwdMeg) {
              this.resetPwdMeg.close();
            }
            resetAgencyPassword(row.id).then(res => {
              if (res.status === 0) {
                let msg = '代理' + row.user_name + ' 密码重置成功，新密码为：' + res.data.password
                this.$message({type: 'success', message: msg,duration: 3000, showClose: true})
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      update(row) {
        if (this.resetPwdMeg) {
          this.resetPwdMeg.close();
        }
        this.show_id = row.id
        this.showUpdate = true
      },
      remove(row) {
        if (this.resetPwdMeg) {
          this.resetPwdMeg.close();
        }
        this.$confirm(`确认删除ID为${row.id}的项么？`, '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAgency(row.id).then(res => {
            if (res.status === 0) {
              this.$message({type: 'success', message: '删除成功!', showClose: true})
              this.getList()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      query() {
        this.q = Object.assign(this.q, {page_no: 1, page_size: 30})
        queryFilter(this.q)
        this.getList()
      },
      reload() {
        this.q = {page_size: 30, page_no: 1}
        this.getList()
      },
      sortlist(sort) {
        this.q.$orderby = sort.prop
        this.getList()
      },
      handleSizeChange(val) {
        this.q.page_size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.q.page_no = val
        this.getList()
      },
      getList() {
        if (this.resetPwdMeg) {
          this.resetPwdMeg.close();
        }
        this.q.agency_type = (this.$route.name ==='Subagent'?'1':'2')
        queryFilter(this.q)
        getAgencyList(this.q).then(res => {
          if (res.status === 0) {
            this.listLoading = false
            res.data.items.forEach(item => {
              if (item.white_ips != null) {
                item.white_ips = item.white_ips.toString()
              }
            })
            this.listData = res.data
            this.listData.items = Array.from(res.data.items, x => Object.assign({}, x, {
              balance: Number(x.balance) / 100,
              warning_amount: Number(x.warning_amount) / 100
            }))
          }
        })
      },
      getMerchantsList() {
        getMerchantsList().then(res => {
          if (res.status === 0) {
            this.MerchantsList = []
            res.data.items.forEach(item=>{
              if(item.enable){
                this.MerchantsList.push(item)
              }
            })
          }
        })
      },
      getAgencyList () {
        getAgencyList({ agency_type: 2, page_size: 1000 }).then(res => {
          if (res.status === 0) {
            this.AgencyMainList = res.data.items
          }
        })
      },
      enbleAgentMag(row) {
        this.$confirm(`确认${row.enable ? '禁用' : '启用'}用户名为${row.user_name}的项么？`, '状态操作'
          , {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
          .then(() => {
            if (row.enable) {
              openAgentMag(row.id).then(res => {
                if (res.status === 0) {
                  this.btnType = 'danger'
                  row.enable = !row.enable
                  this.$message({type: 'success', message: "禁用成功"})
                }
              }).catch(() => {
                this.$message({type: 'error', message: "禁用失败"})
              })
            } else {
              enbleAgentMag(row.id).then(res => {
                if (res.status === 0) {
                  row.enable = !row.enable
                  this.$message({type: 'success', message: "启动成功"})
                  this.btnType = 'info'
                }
              }).catch(() => {
                this.$message({
                  type: 'error',
                  message: "启动失败"
                })
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      typeFormartter(row, column) {
        let columnName = column.property
        if (columnName === 'use_vcode') {
          return row.use_vcode ? '开启' : '关闭'
        } else if (columnName === 'enable') {
          return row.enable ? '可用' : '禁用'
        } else if (columnName === 'working') {
          return row.agency_type == 2 ? '' : row.working ? '工作中' : '休息中'
        } else if (columnName === 'agency_type') {
          return row.agency_type == 1 ? '子代' : row.agency_type == 2 ? '总代' : ''
        } else if (columnName === 'mchs') {
          let mchsList = []
          row.mchs.forEach(item => {
            mchsList.push(item.name)
          })
          return mchsList.toString()
        }
      }
    },
    watch: {
      showUpdate() {
        if (!this.showUpdate) {
          this.getList()
        }
      },
      "$route"(){
        this.listData.items instanceof Array && this.listData.items.splice(0,this.listData.items.length);
        this.q = {page_size: 30, page_no: 1};
        this.getList()
      }
    }
  }
</script>
